package code.juc.uncaughtexception;

import java.util.concurrent.TimeUnit;

/**
 * 正确捕获子线程异常方式: 自定义：Thread.UncaughtExceptionHandler
 */
public class UnCaughtException1 implements Runnable{

    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler("异常捕获器"));
        UnCaughtException1 runnable = new UnCaughtException1();
        for (int i = 0; i < 4; i++) {
            new Thread(runnable).start();
            TimeUnit.SECONDS.sleep(3);
        }
    }

    @Override
    public void run() {
        throwException();
    }

    private void throwException() {
        throw new RuntimeException(Thread.currentThread().getName() + "抛出了异常!");
    }
}

/**
 * 线程异常handler.
 */
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    // handler名称
    private String name;

    public MyUncaughtExceptionHandler(String name) {
        this.name = name;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
        System.out.println("线程中止啦! " + t.getName());
        System.out.println(name + "获取了异常, " + t.getName() + ", 异常" + e);
    }
}


